<template>
  <div class="video-upload-page">
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step title="课程信息" description="创建课程并上传封面" />
      <el-step title="视频集" description="创建视频集并上传视频/封面" />
      <el-step title="分解动作" description="创建动作并上传视频/封面" />
    </el-steps>

    <div v-show="activeStep === 0" class="step-panel">
      <el-form ref="courseFormRef" :model="courseForm" :rules="courseRules" label-width="100px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程简介" prop="courseDesc">
          <el-input type="textarea" :rows="4" v-model="courseForm.courseDesc" placeholder="请输入课程简介" />
        </el-form-item>
        <el-form-item label="课程封面">
          <el-upload
            :action="uploadBase + '/admin/video/upload-course-cover'"
            :headers="uploadHeaders"
            :data="{ courseId: createdCourseId }"
            :disabled="!createdCourseId"
            :show-file-list="false"
            :on-success="onCourseCoverSuccess"
            :before-upload="beforeCourseCoverUpload"
          >
            <el-button type="primary" :disabled="!createdCourseId">上传课程封面</el-button>
          </el-upload>
          <div v-if="courseCoverUrl" class="preview">
            <img :src="courseCoverUrl" alt="course-cover" />
          </div>
          <div v-if="!createdCourseId" class="tip">请先创建课程后再上传封面</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreateCourse" :loading="creatingCourse">创建课程</el-button>
          <el-button type="success" @click="goNextStep" :disabled="!createdCourseId">下一步</el-button>
          <el-button type="success" @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="activeStep === 1" class="step-panel">
      <div class="toolbar">
        <el-button type="primary" @click="openEpisodeDialog" :disabled="!createdCourseId">新增视频集</el-button>
        <el-button @click="goPrevStep">上一步</el-button>
        <el-button type="success" @click="goNextStep" :disabled="episodes.length === 0">下一步</el-button>
      </div>
      <el-table :data="episodes" border stripe>
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="episodeName" label="名称" min-width="160" />
        <el-table-column prop="episodeDesc" label="简介" min-width="200" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="课程视频" min-width="220">
          <template slot-scope="{ row }">
            <div class="row-upload">
              <el-upload
                :action="uploadBase + '/admin/video/upload-course-video'"
                :headers="uploadHeaders"
                :data="{ courseId: createdCourseId, episodeId: row.episodeId }"
                :show-file-list="false"
                :disabled="!row.episodeId"
                :on-success="(res)=>onEpisodeVideoSuccess(res, row)"
                :before-upload="beforeEpisodeVideoUpload"
              >
                <el-button type="primary" :disabled="!row.episodeId">上传视频</el-button>
              </el-upload>
              <a v-if="row.videoUrl" :href="row.videoUrl" target="_blank">预览</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="220">
          <template slot-scope="{ row }">
            <div class="row-upload">
              <el-upload
                :action="uploadBase + '/admin/video/upload-episode-cover'"
                :headers="uploadHeaders"
                :data="{ courseId: createdCourseId, episodeId: row.episodeId }"
                :show-file-list="false"
                :disabled="!row.episodeId"
                :on-success="(res)=>onEpisodeCoverSuccess(res, row)"
                :before-upload="beforeEpisodeCoverUpload"
              >
                <el-button :disabled="!row.episodeId">上传封面</el-button>
              </el-upload>
              <img v-if="row.coverUrl" :src="row.coverUrl" class="thumb" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="新增视频集" :visible.sync="episodeDialogVisible" width="520px">
        <el-form ref="episodeFormRef" :model="episodeForm" :rules="episodeRules" label-width="100px">
          <el-form-item label="名称" prop="episodeName">
            <el-select
              v-model="episodeForm.episodeName"
              filterable
              allow-create
              placeholder="请选择或输入视频集名称"
              @change="handleEpisodeNameChange"
            >
              <el-option
                v-for="item in existingEpisodeNames"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="episodeDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateCourse" :loading="creatingEpisode">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <div v-show="activeStep === 2" class="step-panel">
      <div class="toolbar">
        <el-select v-model="selectedEpisodeId" placeholder="选择视频集" style="width: 260px;" @change="syncSelectedEpisode">
          <el-option v-for="ep in episodes" :key="ep.episodeId" :label="ep.episodeName" :value="ep.episodeId" />
        </el-select>
        <el-button type="primary" @click="openActionDialog" :disabled="!selectedEpisodeId">新增分解动作</el-button>
        <el-button @click="goPrevStep">上一步</el-button>
        <el-button type="success" @click="goNextStep" :disabled="!hasActions">完成</el-button>
      </div>

      <el-table :data="actionsOfSelected" border stripe>
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="actionName" label="名称" min-width="160" />
        <el-table-column prop="actionDesc" label="简介" min-width="200" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="动作视频" min-width="220">
          <template slot-scope="{ row }">
            <div class="row-upload">
              <el-upload
                :action="uploadBase + '/admin/video/upload-action-video'"
                :headers="uploadHeaders"
                :data="{ courseId: createdCourseId, episodeId: selectedEpisodeId, actionId: row.actionId }"
                :show-file-list="false"
                :disabled="!row.actionId"
                :on-success="(res)=>onActionVideoSuccess(res, row)"
                :before-upload="beforeActionVideoUpload"
              >
                <el-button type="primary" :disabled="!row.actionId">上传视频</el-button>
              </el-upload>
              <a v-if="row.videoUrl" :href="row.videoUrl" target="_blank">预览</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="220">
          <template slot-scope="{ row }">
            <div class="row-upload">
              <el-upload
                :action="uploadBase + '/admin/video/upload-action-cover'"
                :headers="uploadHeaders"
                :data="{ courseId: createdCourseId, episodeId: selectedEpisodeId, actionId: row.actionId }"
                :show-file-list="false"
                :disabled="!row.actionId"
                :on-success="(res)=>onActionCoverSuccess(res, row)"
                :before-upload="beforeActionCoverUpload"
              >
                <el-button :disabled="!row.actionId">上传封面</el-button>
              </el-upload>
              <img v-if="row.coverUrl" :src="row.coverUrl" class="thumb" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="新增分解动作" :visible.sync="actionDialogVisible" width="520px">
        <el-form ref="actionFormRef" :model="actionForm" :rules="actionRules" label-width="100px">
          <el-form-item label="名称" prop="actionName">
            <el-select
              v-model="actionForm.actionName"
              filterable
              allow-create
              placeholder="请选择或输入分解动作名称"
              @change="handleActionNameChange"
            >
              <el-option
                v-for="item in existingActionNames"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="简介" prop="actionDesc">
            <el-input type="textarea" :rows="3" v-model="actionForm.actionDesc" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="actionForm.sort" :min="0" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="actionDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateAction" :loading="creatingAction">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>

</template>

<script>
import { getToken } from '@/utils/auth'
import { createCourse } from '@/api/video/course'
import { createEpisode,listEpisode,updateEpisode } from '@/api/video/episode'
import { createAction,listAction,updateAction } from '@/api/video/action'

export default {
  name: 'VideoUploadWizard',
  data() {
    return {
      activeStep: 0,
      uploadBase: process.env.VUE_APP_BASE_API || '',
      createdCourseId: null,
      courseForm: {
        courseName: '',
        courseDesc: ''
      },
      courseRules: {
        courseName: [ { required: true, message: '请输入课程名称', trigger: 'blur' } ]
      },
      creatingCourse: false,
      courseCoverUrl: '',

      // episodes
      episodes: [],
      episodeDialogVisible: false,
      existingEpisodeNames: [], // 存储从接口获取的视频集名称列表
      existingEpisodes: [], // 存储从接口获取的完整视频集信息
      episodeForm: {
        episodeName: '',
        episodeDesc: '',
        sort: 0,
        episodeId:'',
      },
      episodeRules: {
        episodeName: [ { required: true, message: '请输入视频集名称', trigger: 'blur' } ]
      },
      creatingEpisode: false,

      // actions
      selectedEpisodeId: null,
      actionsMap: {}, // { [episodeId]: [] }
      actionDialogVisible: false,
      existingActionNames: [], // 存储从接口获取的分解动作名称列表
      existingActions: [], // 存储从接口获取的完整分解动作信息
      actionForm: {
        actionName: '',
        actionDesc: '',
        sort: 0,
        actionId: ''
      },
      actionRules: {
        actionName: [ { required: true, message: '请输入分解动作名称', trigger: 'blur' } ]
      },
      creatingAction: false
    }
  },
  computed: {
    uploadHeaders() {
      const token = getToken()
      return token ? { Authorization: 'Bearer ' + token } : {}
    },
    actionsOfSelected() {
      return this.actionsMap[this.selectedEpisodeId] || []
    },
    hasActions() {
      // 检查是否有任何视频集包含动作
      return Object.values(this.actionsMap).some(actions => actions && actions.length > 0);
    }
  },
  methods: {
    // 打开弹框时加载已有视频集名称
    async openEpisodeDialog() {
      if (!this.createdCourseId) {
        this.$message.warning('请先完成课程创建')
        return
      }

      // 重置表单
      this.episodeForm = { episodeName: '', episodeDesc: '', sort: 0, episodeId: '' }

      try {
        // 调用接口获取已有视频集列表
        const res = await listEpisode()
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          const episodes = res.data || res.rows || []
          // 提取所有视频集名称（去重）
          this.existingEpisodeNames = [...new Set(episodes.map(ep => ep.episodeTitle))]
          // 保存完整的视频集信息以便后续使用
          this.existingEpisodes = episodes
        }
      } catch (e) {
        console.error('获取视频集列表失败:', e)
        // 即使获取失败也不影响创建新视频集
      }

      this.episodeDialogVisible = true
    },

    goBack() {
      this.$router.back()
    },
    goNextStep() {
      if (this.activeStep < 2) {
        this.activeStep += 1
      } else if (this.activeStep === 2) {
        // 完成整个流程，跳转到课程列表页面
        this.$message.success('课程创建完成！')
        // 跳转到视频管理下的课程列表页面，这样可以显示侧边栏菜单
        this.$router.back()
      }
    },
    goPrevStep() {
      if (this.activeStep > 0) this.activeStep -= 1
    },
    async handleCreateCourse() {
      this.$refs.courseFormRef.validate(async (valid) => {
        if (!valid) return
        this.creatingCourse = true
        try {
          const res = await createCourse(this.courseForm)
          if (res && (res.code === 200 || res.code === 0 || res.success)) {
            // ruoyi 后端通常返回 rows/affected，通过 toAjax -> AjaxResult
            // 课程创建后需要获取 courseId，假设后端返回 data 或从后续详情接口获取
            const id = (res.data && (res.data.courseId || res.data.id)) || res.courseId || null
            if (id) {
              this.createdCourseId = id
              this.$message.success('课程创建成功')
            } else {
              this.$message.warning('课程创建成功，但未返回 courseId，请确认后端返回值')
            }
          } else {
            this.$message.error(res.msg || '创建课程失败')
          }
        } catch (e) {
          this.$message.error('创建课程失败')
        } finally {
          this.creatingCourse = false
        }
      })
    },
    beforeCourseCoverUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) this.$message.error('封面大小不能超过 10MB!')
      if (!this.createdCourseId) this.$message.warning('请先创建课程')
      return isLt10M && !!this.createdCourseId
    },
    onCourseCoverSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.courseCoverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },

    // 更新课程信息（包含视频集）
    handleUpdateCourse() {
      this.$refs.episodeFormRef.validate(async (valid) => {
        if (!valid) return
        this.creatingEpisode = true
        try {
          // 查找已存在的视频集ID
          let episodeId = ''
          const existingEpisode = this.existingEpisodes?.find(ep => ep.episodeTitle === this.episodeForm.episodeName)
          if (existingEpisode) {
            episodeId = existingEpisode.episodeId
          }

          // 准备payload - 假设需要传递课程ID和视频集信息
          const payload = {
            courseId: this.createdCourseId,
            episodeId: episodeId,
            episodeTitle: this.episodeForm.episodeName,
            episodeDesc: this.episodeForm.episodeDesc,
            sort: this.episodeForm.sort
          }

          // 调用更新接口
          const res = await updateEpisode(payload)

          if (res && (res.code === 200 || res.code === 0 || res.success)) {
            this.$message.success('视频集更新成功')

            // 更新本地数据（如果需要）
            const episodeId = res.data?.episodeId || Date.now() // 假设后端返回了episodeId
            this.episodes.push({
              episodeId,
              episodeName: this.episodeForm.episodeName,
              episodeDesc: this.episodeForm.episodeDesc,
              sort: this.episodeForm.sort,
              videoUrl: '',
              coverUrl: ''
            })

            // 关闭弹窗
            this.episodeDialogVisible = false
          } else {
            this.$message.error(res.msg || '更新失败')
          }
        } catch (e) {
          console.error('更新视频集失败:', e)
          this.$message.error('更新视频集失败')
        } finally {
          this.creatingEpisode = false
        }
      })
    },
    beforeEpisodeVideoUpload(file) {
      const ok = file.size < 1024 * 1024 * 1024
      if (!ok) this.$message.error('课程视频不能超过 1GB!')
      return ok
    },
    onEpisodeVideoSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.videoUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeEpisodeCoverUpload(file) {
      const ok = file.size < 5 * 1024 * 1024
      if (!ok) this.$message.error('视频集封面不能超过 5MB!')
      return ok
    },
    onEpisodeCoverSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.coverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },

    syncSelectedEpisode() {
      if (!this.actionsMap[this.selectedEpisodeId]) this.$set(this.actionsMap, this.selectedEpisodeId, [])
    },
    // 处理视频集名称变化
    handleEpisodeNameChange(val) {
      // 查找匹配的视频集
      const matchedEpisode = this.existingEpisodes.find(ep => ep.episodeTitle === val)
      if (matchedEpisode) {
        // 如果找到匹配的视频集，设置episodeId和其他字段
        this.episodeForm.episodeId = matchedEpisode.episodeId
        this.episodeForm.episodeDesc = matchedEpisode.episodeDesc
        this.episodeForm.sort = matchedEpisode.sort
      } else {
        // 如果是新视频集，清空episodeId
        this.episodeForm.episodeId = ''
        this.episodeForm.episodeDesc = ''
        this.episodeForm.sort = 0
      }
    },
    // 打开弹框时加载已有分解动作名称
    async openActionDialog() {
      if (!this.selectedEpisodeId) {
        this.$message.warning('请先选择视频集')
        return
      }

      // 重置表单
      this.actionForm = { actionName: '', actionDesc: '', sort: 0, actionId: '' }

      try {
        // 调用接口获取已有分解动作列表
        const res = await listAction()
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          const actions = res.data || res.rows || []
          // 提取所有分解动作名称（去重）
          this.existingActionNames = [...new Set(actions.map(action => action.actionTitle))]
          // 保存完整的分解动作信息以便后续使用
          this.existingActions = actions
        }
      } catch (e) {
        console.error('获取分解动作列表失败:', e)
        // 即使获取失败也不影响创建新分解动作
      }

      this.actionDialogVisible = true
    },
    // handleCreateAction方法已废弃，使用handleUpdateAction替代
    // handleCreateAction() {
    //   this.$refs.actionFormRef.validate(async (valid) => {
    //     if (!valid) return
    //     this.creatingAction = true
    //     try {
    //       const payload = { ...this.actionForm, courseId: this.createdCourseId, episodeId: this.selectedEpisodeId }
    //       const res = await createAction(payload)
    //       if (res && (res.code === 200 || res.code === 0 || res.success)) {
    //         const actionId = (res.data && (res.data.actionId || res.data.id)) || res.actionId || null
    //         const row = { ...payload, actionId, videoUrl: '', coverUrl: '' }
    //         const list = this.actionsMap[this.selectedEpisodeId] || []
    //         list.push(row)
    //         this.$set(this.actionsMap, this.selectedEpisodeId, list)
    //         this.$message.success('新增分解动作成功')
    //         this.actionDialogVisible = false
    //       } else {
    //         this.$message.error(res.msg || '新增分解动作失败')
    //       }
    //     } catch (e) {
    //       this.$message.error('新增分解动作失败')
    //     } finally {
    //       this.creatingAction = false
    //     }
    //   })
    // },
    beforeActionVideoUpload(file) {
      const ok = file.size < 512 * 1024 * 1024
      if (!ok) this.$message.error('动作视频不能超过 512MB!')
      return ok
    },
    onActionVideoSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.videoUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeActionCoverUpload(file) {
      const ok = file.size < 5 * 1024 * 1024
      if (!ok) this.$message.error('动作封面不能超过 5MB!')
      return ok
    },
    onActionCoverSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.coverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 处理分解动作名称变化
    handleActionNameChange(val) {
      // 查找匹配的分解动作
      const matchedAction = this.existingActions.find(action => action.actionTitle === val)
      if (matchedAction) {
        // 如果找到匹配的分解动作，设置actionId和其他字段
        this.actionForm.actionId = matchedAction.actionId
        this.actionForm.actionDesc = matchedAction.actionDesc
        this.actionForm.sort = matchedAction.sort
      } else {
        // 如果是新分解动作，清空actionId
        this.actionForm.actionId = ''
        this.actionForm.actionDesc = ''
        this.actionForm.sort = 0
      }
    },
    // 更新分解动作信息
    async handleUpdateAction() {
      this.$refs.actionFormRef.validate(async (valid) => {
        if (!valid) return
        this.creatingAction = true
        try {
          // 查找已存在的分解动作ID
          let actionId = ''
          const existingAction = this.existingActions?.find(action => action.actionTitle === this.actionForm.actionName)
          if (existingAction) {
            actionId = existingAction.actionId
          }

          // 准备payload
          const payload = {
            episodeId: this.selectedEpisodeId,
            actionTitle: this.actionForm.actionName,
            actionDesc: this.actionForm.actionDesc,
            sort: this.actionForm.sort
          }

          // 如果是更新已存在的分解动作，添加actionId
          if (actionId) {
            payload.actionId = actionId
          }

          // 调用更新接口
          const res = await updateAction(payload)

          if (res && (res.code === 200 || res.code === 0 || res.success)) {
            this.$message.success('分解动作更新成功')

            // 更新本地数据
            const actionId = res.data?.actionId || payload.actionId || Date.now()
            const actionItem = {
              actionId,
              actionName: this.actionForm.actionName,
              actionDesc: this.actionForm.actionDesc,
              sort: this.actionForm.sort,
              videoUrl: '',
              coverUrl: ''
            }

            // 添加到actionsMap中
            if (!this.actionsMap[this.selectedEpisodeId]) {
              this.$set(this.actionsMap, this.selectedEpisodeId, [])
            }
            this.actionsMap[this.selectedEpisodeId].push(actionItem)

            // 关闭弹窗
            this.actionDialogVisible = false

            // 如果当前步骤是第2步（分解动作），则提示用户可以继续操作
            if (this.activeStep === 2) {
              this.$message.success('分解动作创建成功，您可以继续添加更多动作或点击"完成"结束流程')
            }
          } else {
            this.$message.error(res.msg || '更新失败')
          }
        } catch (e) {
          console.error('更新分解动作失败:', e)
          this.$message.error('更新分解动作失败')
        } finally {
          this.creatingAction = false
        }
      })
    }
  }
}
</script>

<style scoped>
.video-upload-page {
  padding: 16px;
}
.step-panel {
  margin-top: 20px;
}
.toolbar {
  margin: 12px 0;
}
.preview img,
.thumb {
  width: 120px;
  height: 68px;
  object-fit: cover;
  margin-left: 12px;
  border: 1px solid #eee;
}
.row-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}
.tip { color: #909399; margin-top: 6px; }
</style>



